// auth-middleware.js
const rbac = require('./rbac');
const auth = require('./auth');

// 权限检查中间件
const checkPermission = (permission) => {
  const userInfo = auth.getUserInfo();
  if (!userInfo || !userInfo.role) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/login'
      });
    }, 1500);
    return false;
  }

  if (!rbac.hasPermission(userInfo.role, permission)) {
    wx.showToast({
      title: '没有操作权限',
      icon: 'none'
    });
    return false;
  }

  return true;
};

// 检查是否是管理员
const requireAdmin = () => {
  const userInfo = auth.getUserInfo();
  if (!userInfo || !rbac.isAdmin(userInfo.role)) {
    wx.showToast({
      title: '需要管理员权限',
      icon: 'none'
    });
    return false;
  }
  return true;
};

// 检查是否是商家
const requireMerchant = () => {
  const userInfo = auth.getUserInfo();
  if (!userInfo || !rbac.isMerchant(userInfo.role)) {
    wx.showToast({
      title: '需要商家权限',
      icon: 'none'
    });
    return false;
  }
  return true;
};

// 检查是否已登录
const requireLogin = () => {
  const userInfo = auth.getUserInfo();
  if (!userInfo) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/login'
      });
    }, 1500);
    return false;
  }
  return true;
};

module.exports = {
  checkPermission,
  requireAdmin,
  requireMerchant,
  requireLogin
}; 